package com.itheima.framework.context.support;

import com.itheima.framework.beans.BeanDefinition;
import com.itheima.framework.beans.factory.support.BeanDefinitionReader;
import com.itheima.framework.beans.factory.support.BeanDefinitionRegistry;
import com.itheima.framework.context.ApplicationContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zzw
 * @date 2025/11/15
 * @description 非延时加载
 */
public abstract class AbstractApplicationContext implements ApplicationContext {

    protected BeanDefinitionReader beanDefinitionReader;

    // 存储bean的容器，key是bean的id，value是bean对象
    protected Map<String, Object> singletonObjects = new ConcurrentHashMap<>();

    // 存储配置文件的路径
    protected String configLocation;

    @Override
    public void refresh() throws IllegalStateException, Exception {

        // 加载BeanDefinition
        beanDefinitionReader.loadBeanDefinitions(configLocation);

        // 初始化bean
        finishBeanInitialization();
    }

    // 初始化bean
    private void finishBeanInitialization() throws Exception {
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        String[] beanNames = registry.getBeanDefinitionNames();

        for (String beanName : beanNames) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
            getBean(beanName);
        }
    }
}
